﻿using System;
using System.IO;
using USU.MetricsMonitor.Common;
using System.Diagnostics;

namespace USU.MetricsMonitor.DiffProvider
{
    /// <summary>
    /// Для работы этого класса должен быть установлен Subversion, 
    /// т.к. используется svn.exe
    /// </summary>
    public class SvnDiffProvider : BaseDiffProvider
    {
        public static readonly string SvnExeArgumentsPattern = @"diff -c {0} ""{1}""";
        public static readonly string DiffFilePattern = "{0}.diff";

        public SvnDiffProvider(string repositaryPath, string diffLocalDirectory)
            : base(repositaryPath, diffLocalDirectory) { }


        public override Stream GetStream(Revision rev)
        {
            string fileDiffPath = Path.Combine(DiffLocalDirectory, String.Format(DiffFilePattern, rev.Long()));

            if (!File.Exists(fileDiffPath))
            {
                GetNetDiff(fileDiffPath, rev);
            }

            FileStream file = File.Open(fileDiffPath, FileMode.Open, FileAccess.Read);
            return file;
        }

        private void GetNetDiff(string fileDiffPath, Revision rev)
        {
            string tempDiffPath = Path.Combine(DiffLocalDirectory, String.Format(DiffFilePattern, "temp"));
            try{
                using (var file = File.Open(tempDiffPath, FileMode.Create, FileAccess.Write))
                using (var consoleApp = new ConsoleApplication(Utils.SvnExeFileName,String.Format(SvnExeArgumentsPattern, rev, RepositaryPath)))
                {
                    consoleApp.RedirectOutputTo(file);
                    consoleApp.WaitForExit();
                }
            }
            catch (ConsoleApplicationException e)
            {
                throw new DiffProviderException("Ошибка при получении diff'а", e);
            }
            File.Move(tempDiffPath, fileDiffPath);
        }
    }
}
